import React, { Component,Fragment } from 'react';
import {Table,Button,Icon,Form,Input,Card,Modal,message,Popconfirm} from 'antd';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import {PAGE_SIZE} from './constants';
const ENTITY = 'resource';
//dva-loading
export default  @connect(state=>(
  {...state[ENTITY],loading:state.loading.models[ENTITY]}
)) class componentName extends Component {
  save = (payload)=>{
    this.props.dispatch({
      type:`${ENTITY}/save`,
      payload
    });
  }
  onAdd = ()=>{
    this.save({editVisible:true});
  }
  onEditCancel = ()=>{
    this.save({editVisible:false});
  }
  onEditOk = ()=>{
    this.editForm.props.form.validateFields((err,payload)=>{
      if(err){
        message.error(err);
      }else{
        this.props.dispatch({
          type:this.props.isCreate?`${ENTITY}/create`:`${ENTITY}/update`,
          payload
        });
      }
    });
  }
  onEdit  = (record)=>{
    this.save({editVisible:true,record,isCreate:false});
  }
  onDel = (payload)=>{
    this.props.dispatch({
      type:`${ENTITY}/del`,
      payload
    });
  }
  onDelAll = ()=>{
    this.props.dispatch({
      type:`${ENTITY}/delAll`
    });
  }
  handleSearch = ()=>{
    let values = this.searchForm.props.form.getFieldsValue();
    let where = Object.keys(values).reduce((memo,key)=>{
      if(values[key]){
        memo[key] = values[key];
      }
      return memo;
    },{});
    this.props.dispatch({
      type:`${ENTITY}/search`,
      where
    })
  }
  render() {
    const columns = [
      {title:'名称',dataIndex:'name',key:'name'},
      {title:'路径',dataIndex:'key',key:'key'},
      {title:'图标',dataIndex:'icon',key:'icon'},
      {title:'操作',key:'operation',render:(value,record)=>{
         return (
          <Button.Group>
             <Button type="warning" onClick={()=>this.onEdit(record)}>编辑</Button>
             <Popconfirm
                 okText="确认"
                 cancelText="取消"
                 title="请问你是否确定要删除此记录?"
                 onConfirm={()=>this.onDel(record.id)}
             >
               <Button style={{marginLeft:8}} type="danger">删除</Button>
             </Popconfirm>
          </Button.Group>
         )
      }}
    ]
    const {list,pageNum,total,loading,editVisible,
      isCreate,record,selectedRowKeys} = this.props;
    const pagination = {
      current:pageNum,//当前的页码
      pageSize:PAGE_SIZE,//每页的条数
      total,
      showQuickJumper:true,
      showTotal:(total)=>{
        return `共计${total}条`;
      },
      onChange : (pageNum)=>{
        //我需要跳到指定的页码
        // routerRedux.push(`/admin/user?pageNum=1`);
        this.props.dispatch(routerRedux.push({
          pathname:`/admin/${ENTITY}`,
          query:{pageNum}
        }));
      }
    }
    const rowSelection = {
      type:'checkbox',
      selectedRowKeys,
      onChange: (selectedRowKeys,selectedRows)=>{
        this.save({selectedRowKeys});
      }
    }
    return (
      <Fragment>
        <Card>
          <SearchForm
           handleSearch={this.handleSearch}
           wrappedComponentRef={inst=>this.searchForm = inst}
          />
        </Card>
        <Card>
          <Button.Group>
            <Button type="warning" onClick={this.onAdd}>添加</Button>
            <Button type="danger" onClick={this.onDelAll}>全部删除</Button>
          </Button.Group>
          <Table
            rowKey={row=>row.id}
            columns={columns}
            dataSource={list}
            loading={loading}
            pagination={pagination}
            rowSelection={rowSelection}
            onRow={
              (record)=>(
                {
                  onClick:()=>{
                    let selectedRowKeys = this.props.selectedRowKeys;
                    let index = selectedRowKeys.indexOf(record.id);
                    if(index==-1){
                      selectedRowKeys = [...selectedRowKeys,record.id]
                    }else{
                      selectedRowKeys = selectedRowKeys.filter(item=>item != record.id);
                    }
                    this.save({selectedRowKeys});
                  }
                }
              )
            }
          />
          <EditModal
            wrappedComponentRef={instance => this.editForm = instance}
            visible={editVisible}
            isCreate={isCreate}
            onOk={this.onEditOk}
            onCancel={this.onEditCancel}
            record={record}
          />
        </Card>
      </Fragment>
    )
  }
}

@Form.create()
class SearchForm extends Component{
  render(){
    let {form:{getFieldDecorator},handleSearch} = this.props;
    return(
      <Form layout="inline">
          <Form.Item label="名称">
            {
               getFieldDecorator('name',{})(<Input/>)
            }
          </Form.Item>
          <Form.Item>
            <Button onClick={handleSearch} shape="circle" icon="search"></Button>
          </Form.Item>
        </Form>
    )
  }
}

@Form.create()
class EditModal extends Component{
  render(){
    let {form:{getFieldDecorator},visible,isCreate,onOk,onCancel,record} = this.props;
    let formItemLayout = {
      labelCol:{span:4},
      wrapperCol:{span:20}
    }
    return (
      <Modal
         destroyOnClose
         title={isCreate?'增加':'编辑'}
         visible={visible}
         onOk={onOk}
         onCancel={onCancel}
      >
        <Form>
          <Form.Item >
            {
               getFieldDecorator('id',{
                 initialValue:record.id,
               })(<Input  type="hidden"/>)
            }
           </Form.Item>
           <Form.Item >
            {
               getFieldDecorator('parent_id',{
                 initialValue:0,
               })(<Input  type="hidden"/>)
            }
           </Form.Item>
          <Form.Item label="名称" {...formItemLayout}>
            {
               getFieldDecorator('name',{
                 initialValue:record.name,
                 rules:[{required:true,message:'名称必须输入'}]
               })(<Input/>)
            }
          </Form.Item>
          <Form.Item label="路径" {...formItemLayout}>
            {
               getFieldDecorator('key',{
                 initialValue:record.key,
                 rules:[{required:true,message:'路径必须输入'}]
               })(<Input/>)
            }
          </Form.Item>
          <Form.Item label="图标" {...formItemLayout}>
            {
               getFieldDecorator('icon',{
                 initialValue:record.icon,
                 rules:[{required:true,message:'图标必须输入'}]
               })(<Input/>)
            }
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}